import { getHeroListAPI } from "../../api/hero"
import Variable from "../../constants/index"
import { Hero } from "../types/hero"

// pages/search/search.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    heroList: [] as Hero[],
    word: "", // 定义搜索字段
    searchWordsList: [] as string[] // 搜索历史记录
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {

  },
 async searchList(){
    if(this.data.word){
      wx.showLoading({title:'加载中'})
      this.setData({
        heroList:await getHeroListAPI({q:this.data.word}),
        searchWordsList:[...new Set([this.data.word,...this.data.searchWordsList])]
      },()=>{
        wx.setStorageSync(Variable.SEARCH_WORD_KEY,JSON.stringify(this.data.searchWordsList))
        wx.hideLoading()
      })
    }else{
      this.setData({
        heroList:[]
      })
    }
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  search1(event: { mark: { word: any } }){
    this.setData({
      word:event.mark?.word
    },()=>{
      this.searchList()
    })
  },
  delAll(){
    this.setData({
      searchWordsList:[]
    },()=>{
      wx.removeStorageSync(Variable.SEARCH_WORD_KEY)
    })
  },
  delWord(event: { mark: { word: string } }){
    this.setData({
      searchWordsList:this.data.searchWordsList.filter(item=>item!==event.mark?.word)
    },()=>{
      wx.setStorageSync(Variable.SEARCH_WORD_KEY,JSON.stringify(this.data.searchWordsList)) 
    })
  },
  toDetail(event:  WechatMiniprogram.TouchEvent) {
    wx.navigateTo({
      url: `/pages/hero_detail/hero_detail?heroId=${event.mark?.heroId}`
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getHistoryList()
  },
  getHistoryList(){
    this.setData({
      searchWordsList:JSON.parse(wx.getStorageSync(Variable.SEARCH_WORD_KEY) || "[]") as string[]
    })
    
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})